<?
//------------------------------------------------------------------------------
//
// bugs blablabla
//
//------------------------------------------------------------------------------




//------------------------------------------------------------------------------


function get_users_bugs($uid, $count=10)
{
   if( !($uid>0 && $count>0) ) return false;

   $q = 'select `bugs`.*, `levels`.`id` as `level`
                        from `bugs`
                        inner join `levels` on `levels`.`id`=`bugs`.`level_id`
                        where `user_id`=?d order by `date` desc limit ?d';

   $db = mysql_init();

   $bugs = $db->select($q, $uid, $count);

   return $bugs;
}


//------------------------------------------------------------------------------


function set_bug_status($bid, $status)
{
   if( !($bid>0 && $status>0) ) return 'can`t set new status!';
   
   $q = 'update `bugs` set status=? where `id`=?d';

   $db = mysql_init();
   
   $r = $db->query($q, $status, $bid);
   
   return $r;
}

//------------------------------------------------------------------------------


function add_new_bug($bug, $comment, $files)
{
   if( !(is_array($bug) && is_array($comment)) ) return false;
   
   unset($bug['level']);
   
   $db = mysql_init();

   $q = 'insert into `bugs` (?#) values(?a)';

   $nbid = $db->query($q, array_keys($bug), array_values($bug));
   
   $comment['bug_id'] = $nbid;
   
   $ncid = add_new_comment($comment, $files);
   
   return $nbid;
}

//------------------------------------------------------------------------------


function edit_bug($bug, $comment=false, $files)
{
   if( !isset($bug['id']) ) return false;
   
   $db = mysql_init();
   
   $bid = $bug['id'];
   unset($bug['id']);
   unset($bug['level']);

   $q = 'update `bugs` set ?a where `id`=?d';

   $db->query($q, $bug, $bid);

   if(isset($comment['id'])) edit_comment($comment, $files);
      
   return $bid;

}

//------------------------------------------------------------------------------

function deletebug($bid)
{
   if( !($bid)>0 ) return true;

   deleteBugComments($bid);

   $q = 'delete from `bugs` where `id`=?d';

   $db = mysql_init();

   $db->query($q, $bid);
   
   return $bid;
}

//------------------------------------------------------------------------------


function is_bug($bid, $bug=false, $level=_default_level_num)
{
   if( !($bid>0) ) return false;
   if(!is_array($bug))
   {
      $level = ($level>0) ? $level : _default_level_num;

      $q = 'select `bugs`.*, `levels`.`num` as `level`
                              from `bugs`
                              inner join `levels` on `levels`.`id`=`bugs`.`level_id` where `levels`.`num` <= ?d
                              and `bugs`.`id`=?d limit 1';

      $db = mysql_init();

      $bug = $db->selectRow($q, $level, $bid);
   }
   
   if(isset($bug['id']) && $bug['id'] == $bid) return $bug;
   else return false;

}

//------------------------------------------------------------------------------


function is_his_bug($bid, $bug=false, $user)
{
   $bug = is_bug($bid, $bug, $user['level']);
   
   if(isset($bug['user_id']) && $bug['user_id'] == $user['id']) return true;
   else return false;
}


//------------------------------------------------------------------------------


function get_bug($bid, $level=_default_level_num)
{
   $bug = is_bug($bid, false, $level);

   if( !$bug ) return new_bug();

   $db = mysql_init();

   $q = 'select * from `comments` where `bug_id`=?d and `isfirst`=1 limit 1';
   
   $bug['comment'] = $db->selectRow($q, $bug['id']);
   
   return $bug;
}

//------------------------------------------------------------------------------


function get_bugs($filter=false, $xfilter=false, $level=_default_level_num, $current_page=0, $favs=0)   // xfilter = very special array with just one pair of `key` => `value`
{
   $level = ($level>0) ? $level : _default_level_num;

   $favs = $favs ? 'and `fav`=1 ' : '';
   
   $fx = is_array($xfilter) ? ( 'and `'. key($xfilter) .'`="'. justdigs(current($xfilter)) .'"' ) : '';

   $q = (!$filter) ? 'select `bugs`.*, `levels`.`num` as `level` from `bugs`
                                          inner join `levels` on `levels`.`id`=`bugs`.`level_id` where `levels`.`num` <= ?d
                                          '.$favs.'
                                          '.$fx.' order by `date` desc limit ?d, ?d'
                                          
                   : "select `bugs`.*, `levels`.`num` as `level` from `bugs`
                                          inner join `levels` on `levels`.`id`=`bugs`.`level_id` where `levels`.`num` <= ?d
                                          ".$favs."
                                          ".$fx." and ( (`title` like '%".justwords($filter)."%') or (`tags` like '%".justwords($filter)."%') or (`date` like '%".justwords($filter)."%') ) order by `date` desc limit ?d, ?d ";

   global $_x_counter;

   $db = mysql_init();

   $bugs = $db->selectPage($_x_counter, $q, $level, ($current_page * _bugs_on_page), _bugs_on_page);

   return $bugs;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------


function html_bugform($current_user, $bid=0, $bug=0)
{
   if( !( isset($bug['id']) && $bug['id']>0 ) ) $bug = get_bug($bid, $current_user['level']);
   
   $form_tpl  = get_template('bugs_newform.html');
   $form_kwds = array(  '_ID_',
                        '_TITLE_',
                        '_DATE_',
                        '_AUTHORID_',
                        '_AUTHORNAME_',
                        '_COMMENTID_',
                        '_COMMENT_',
                        '_SL-RATE1_',
                        '_SL-RATE2_',
                        '_SL-RATE3_',
                        '_STATUSOPTS_',
                        '_LEVELOPTS_',
                        '_PLACEOPTS_',
                        '_TYPEOPTS_',
                        '_ATTACHMENTS_',
                        '_TAGS_',
                        '_BASEDOMAIN_');
                        
   $sl_rate = opts_selected(3, $bug['rate']);

   $statuses = list_ref_opts('statuses', $bug['status']);
   $places =   list_ref_opts('places',   $bug['place_id']);
   $types  =   list_ref_opts('types' ,   $bug['type_id']);
   $levels =   list_ref_opts('levels',   $bug['level_id'], $current_user['level'] );
   
   
   $bug_author = get_user($bug['user_id']);

   if($bug_author['id'] == _anonymous_id && $bug['id']>0 )  // edit bug mode in anonymous mode
   {
      $bug_author['name'] = $bug['comment']['user_name'];
   }
   elseif($bug['id']==0)
   {
      $bug_author['name'] = $current_user['name']; // new bug
      $bug_author['id'] = $current_user['id'];
   }

   $date = now();

   $attachments = html_attachlist($bug['comment']['id'], true);
   
   $bug_author['name'] = ($bug_author['id'] == _anonymous_id) ? '' : $bug_author['name'];

   $r = array( $bug['id'],
               $bug['title'],
               $date,
               $bug_author['id'],
               $bug_author['name'],
               $bug['comment']['id'],
               $bug['comment']['text'],
               $sl_rate[1],
               $sl_rate[2],
               $sl_rate[3],
               $statuses,
               $levels,
               $places,
               $types,
               $attachments,
               $bug['tags'],
               _basedomain);
   
   $form = str_replace($form_kwds, $r, $form_tpl);
   
   return $form;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------


function html_bugpage($bug, $user, $currentpage)
{
   if(isset($bug['id']) && count($bug)>0)
   {
      $bugpage_tpl  = get_template('bug_page.html');
      $bugpage_kwds = array('_BID_',
                            '_RATE_',
                            '_TITLE_',
                            '_FAV_',
                            '_EDITLNK_',
                            '_DELETELNK_',
                            '_DATE_',
                            '_STATUSCHANGEFUNC_',
                            '_STATUSES_',
                            '_STATUS_',
                            '_LEVEL_',
                            '_TYPE_',
                            '_PLACE_',
                            '_AUTHOR_',
                            '_AUTHORCOMMENT_',
                            '_AUTHORIP_',
                            '_AUTHORLOGIN_',
                            '_BUGDESC_',
                            '_ATTACHMENTS_',
                            '_TAGS_',
                            '_COMMENTS_',
                            '_COMMENTFORM_',
                            '_BASEDOMAIN_'
                            );
                            

      $bug_author   = get_user($bug['user_id']);
      $bug_desc     = get_first_comment($bug['id']);

      //------------------------------------------------------------------------

      global $_x_counter;

      $bug_comments = get_bug_comments($bug['id'], $currentpage);

      $cmts_pager   = ''; //html_pager(_comments_on_page, $currentpage);

      $html_cmts    = html_bug_comments($bug_comments, $currentpage, $user, $cmts_pager);
      
      //------------------------------------------------------------------------

      $statuschanger = '';
      $statuses = '';

      $caneditown = ( is_his_bug($bug['id'], $bug, $user) && check_user_right('bugs', 'edit_own', $user['rights']) );
      $caneditall = check_user_right('bugs', 'edit_other', $user['rights']);
      $candelete  = check_user_right('bugs', 'delete_bugs', $user['rights']);
      
      $bugedit = ($caneditall || $caneditown) ? get_template('bug_page_edit_lnk.html') : '';

      $bugdelete = ( ($caneditall || $caneditown) && $candelete ) ? get_template('bug_page_delete_lnk.html') : '';
      
      //------------------------------------------------------------------------
      
      if($bugedit!='')
      {
         $bugedit  = $bugedit ; //str_replace('_ID_', $bug['id'], $bugedit);
      }
      
      if($bugdelete!='')
      {
         $bugdelete = $bugdelete; //str_replace('_ID_', $bug['id'], $bugdelete);
      }
      
      $infavs = !check_user_right('bugs', 'set_fav', $user['rights'])
                              ?
                               ( $bug['fav']==1 ? get_template('bug_page_fav.html')
                                                : get_template('bug_page_nofav.html') )
                              :
                               ( $bug['fav']==1 ? get_template('bug_page_fav_edit.html')
                                                : get_template('bug_page_nofav_edit.html') )
                              ;

      
      //------------------------------------------------------------------------
      
      if($bugedit!='' || check_user_right('bugs', 'edit_status', $user['rights']) )
      {
         $statuschanger = 'changestatus()';
         $statuses = list_ref_opts('statuses', $bug['status']);
      }
      
      //------------------------------------------------------------------------
      
      $commentform = '<!-- can`t comment -->';
      
      if( check_user_right('bugs', 'add_comment', $user['rights']) )
      {
         $cform_tpl = get_template('bug_page_comment_field.html');
         $cform_kws = array('_UID_', '_CID_', '_BID_');
         
         $r = array($user['id'], 0, $bug['id']);

         $commentform = str_replace($cform_kws, $r, $cform_tpl);
         unset($cform_tpl, $cform_kws, $r);
      }
      
      //------------------------------------------------------------------------

      $r = array( $bug['id'],
                  $bug['rate'],
                  $bug['title'],
                  $infavs,
                  $bugedit,
                  $bugdelete,
                  datef($bug['date']),
                  $statuschanger,
                  $statuses,
                  trim_spaces_rfc( get_rfc_item_name('statuses', $bug['status']) ),
                  trim_spaces_rfc( get_rfc_item_name('levels',   $bug['level_id']) ),
                  trim_spaces_rfc( get_rfc_item_name('types',    $bug['type_id']) ),
                  trim_spaces_rfc( get_rfc_item_name('places',   $bug['place_id']) ),
                  $bug_author['name'],
                  $bug_author['comment'],
                  $bug_desc['ip'],
                  $bug_author['login'],
                  $bug_desc['text'],
                  html_attachlist($bug_desc['id']),
                  $bug['tags'],
                  $html_cmts,
                  $commentform,
                  _basedomain);
                  
      $html = str_replace($bugpage_kwds, $r, $bugpage_tpl);
      
      return $html;
   }
   else return get_template('error_nobug.html');
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------


function html_bugslist($filter=false, $xfilter=false, $ajaxmode=false, $level=_default_level_num, $favs=0)
{
   global $_x_counter, $_x_current_page;
   
   $bugs = get_bugs($filter, $xfilter, $level, $_x_current_page, $favs);

   $c = count($bugs);
   
   if($c>0)
   {
      $listrow_tpl = get_template('bugs_list_row.html');
      $listrow_kwd = array(
                            '_RATE_',
                            '_ID_',
                            '_ISFAV_',
                            '_STATUSID_',
                            '_TITLE_',
                            '_TYPE_',
                            '_TYPEID_',
                            '_PLACE_',
                            '_PLACEID_',
                            '_STATUS_',
                            '_DATE_',
                            '_LEVEL_',
                            '_CCOUNTER_',
                            '_BASEDOMAIN_');
                            
      $rows = '';
      
                            
      for($i=0; $i<$c; $i++)
      {
         $bug = $bugs[$i];
         
         $bug['place'] = trim_spaces_rfc( get_rfc_item_name('places', $bug['place_id']) );
         $bug['status_name']= trim_spaces_rfc( get_rfc_item_name('statuses', $bug['status']) );
         $bug['type']  = trim_spaces_rfc( get_rfc_item_name('types',  $bug['type_id']) );
         $bug['level'] = trim_spaces_rfc( get_rfc_item_name('levels', $bug['level_id']) );
         
         $ccounter = count_bug_comments($bug['id']);
         
         $ccounter = ($ccounter>0) ? '+'.$ccounter : '';
         
         $isfav = $bug['fav'] ? get_template('bugs_list_fav.html') : '';

         $r = array(
                     $bug['rate'],
                     $bug['id'],
                     $isfav,
                     $bug['status'],
                     $bug['title'],
                     $bug['type'],
                     $bug['type_id'],
                     $bug['place'],
                     $bug['place_id'],
                     $bug['status_name'],
                     datef($bug['date']),
                     $bug['level'],
                     $ccounter,
                     _basedomain
                   );
                     
         $rows .= str_replace($listrow_kwd, $r, $listrow_tpl);
      }
      
      $alllnk = ($filter || $xfilter) ? get_template('bugs_list_alllnk.html') : '';
      
      $pager = needpager($_x_counter, _bugs_on_page);
      $rows .= ($pager>0) ? html_pager($pager, $_x_current_page) : '';

      if($ajaxmode)
      {
         return $alllnk."\n".$rows;
      }
      else
      {
         $bugslist_tpl = get_template('bugs_list.html');
         $bugslist_kwd = array('_ALLLNK_', '_BUGROWS_', '_SEARCHFIELD_');
         
         $sfield = '';
         
         if(!$xfilter)
         {
            $sfield = get_template('bugs_list_searchfield.html');
         
            $sf_kws = array('_ISFAVS_');
         
            $sfield = str_replace($sf_kws, (int)$favs, $sfield);
         }

         return str_replace($bugslist_kwd, array($alllnk, $rows, $sfield), $bugslist_tpl);
      }

   }
   else return get_template('error_nobugs.html');
}


















?>
